#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>

#define KB 1024
#define MB (1024 * 1024)

void flush_input() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

int main() {
    printf("Process PID: %d\n", getpid());
    int block_size;
    printf("Please input the size of block(MB):> ");
    scanf("%d", &block_size);
    flush_input();
    
    char* block = malloc(block_size * MB);
    if (!block) {
        perror("malloc failed");
        return 1;
    }
    // 预热内存：确保所有页都被实际分配
    for (int i = 0; i < block_size * MB; i += 4 * KB) {
        block[i] = 0;
    }
    printf("Allocated %d MB. Start modifying...\nPress Enter to stop\n", block_size);
    while (1) {
        // 持续写入制造压力
        for (int i = 0; i < block_size * MB; i += 4 * KB) {
            block[i] = (block[i] + 1) % 256; // 修改处：每次+1
        }

        // 非阻塞检查输入
        struct timeval tv = {0, 0};
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(STDIN_FILENO, &fds);
        if (select(STDIN_FILENO+1, &fds, NULL, NULL, &tv) > 0) {
            flush_input();
            break;
        }
    }
    free(block);
    return 0;
}